import { Router } from '@angular/router';
import { MomService } from './../../../../@core/services/mom/mom.service';
import { ProcessService } from 'src/app/@core/services/process/process.service';
import { SelectTechnologyRouteComponent } from './../../../../@shared/components/select-technology-route/select-technology-route.component';
import { SelectMaterialComponent } from './../../../../@shared/components/select-material/select-material.component';
import { Component, ViewChild } from '@angular/core';
import { DValidateRules, EditableTip, FormLayout, TableWidthConfig, TreeComponent, DialogService, ToastService } from 'ng-devui';
import { Part, ProcessDetail } from 'src/app/@core/data/MomData';
import { PreViewmMomComponent } from '../pre-viewm-mom/pre-viewm-mom.component';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { delay, max, of } from 'rxjs';
import { PagesComponent } from 'src/app/pages/pages.component';
@Component({
  selector: 'app-add-mom',
  templateUrl: './add-mom.component.html',
  styleUrls: ['./add-mom.component.scss']
})
export class AddMOMComponent {
  @ViewChild('basicTree', { static: true }) basicTree: TreeComponent;
  msgs: { severity: any; summary: any; content: any; }[];
  tabActiveId: string | number = '工序';
  value1 = []
  layoutDirection: FormLayout = FormLayout.Horizontal;
  originalProcessNumber: any
  originalPartNumber: any
  data = [
  ];
  MaterialData = [
    {
      number: 1,
      code: null,
      name: null,
      consumption: null,
      loss: null
    }
  ];
  nodes = [];
  Parts: Part[] = [
    {
      partId: null,
      partNum: "",
      partName: "",
      partNumber: null,
      unitUsage: 0,
      lossRate: 0,
      fixedLoss: 0,
      partType: '',
      partUOM: ''
    }
  ]
  iconLeaf = '<span></span>';
  ProcessDetails: ProcessDetail[] = [
    {
      processId: null,
      processNum: "",
      processName: "",
      processNumber: null,
      isFirstInspection: true,
      isOutsourcing: true,
      isInspection: true,
      unitTime: 0,
      pieceWage: 0,
      parts: this.Parts
    }
  ]
  processNumberRule: boolean = false;
  Materials: Part[] = []
  selectNode = this.nodes[0];
  MomData = {
    partId: null,
    partNum: "",
    partName: "",
    version: "",
    technologyRouteId: null,
    technologyRouteNum: "",
    technologyRouteName: "",
    startDate: "",
    endDate: "",
    isApproval: false,
    fileURL: '',
    momProcesses: this.ProcessDetails,
    Materials: this.Materials
  };
  MOM = {
    partId: null,
    partNum: "",
    partName: "",
    version: "",
    technologyRouteId: null,
    technologyRouteNum: "",
    technologyRouteName: "",
    startDate: "",
    endDate: "",
    isApproval: false,
    momProcesses: []
  }
  reg: RegExp = /^(0\.\d+|[1-9]\d*(\.\d+)?)$/;
  display = false;
  options = [];
  processOptions: []
  isClicked = false;
  nameEditing: boolean;
  treeData: any
  editableTip = EditableTip.btn;
  momFormRules: { [key: string]: DValidateRules } = {
    partNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '物料编码不能为空' }
      ]
    },
    partName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '物料名称不能为空' }
      ]
    },
    version: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '版本不能为空' },
        { pattern: /^[^\s]*$/, message: '*工序编码不能包含空格' }
      ]
    },
    technologyRouteNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '工艺路线编码不能为空' }
      ]
    },
    technologyRouteName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '工艺路线名称不能为空' }
      ]
    },
    startDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '有效期不能为空' },
        { requiredTrue: this.value1.length == 2, message: '*有效期不能为空' }
      ]
    },
    endDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '有效期不能为空' },
        { requiredTrue: this.value1.length == 2, message: '*有效期不能为空' }
      ]
    },
    unitTime: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '单位工时不能为空' },
        { pattern: /^(0\.\d+|[1-9]\d*(\.\d+)?)$/, message: '*工时必须为正数且不能为0' }]
    },
    processNumber: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*工序序号不能为空' },
        { pattern: /^[1-9]\d*$/, message: "*工序序号不可为0或负数" }
      ],
      asyncValidators: [
        {
          sameNumber: this.processNumber.bind(this), message: {
            'zh-cn': '*工序序号' + '重复',
          }
        }
      ]
    },
    pieceWage: {
      messageShowType: 'text',
      validators: [
        { pattern: /^(0(\.\d+)?|[1-9]\d*(\.\d+)?)$/, message: '*计件工资必须为非负数' }
      ]
    },
  }
  devuiTableWidthConfig: TableWidthConfig[] = [
    {
      field: 'number',
      width: '150px',
    },
    {
      field: 'number',
      width: '150px',
    },
    {
      field: 'number',
      width: '150px'
    },
    {
      field: 'code',
      width: '150px'
    },
    {
      field: 'name',
      width: '150px'
    },
    {
      field: 'consumption',
      width: '150px'
    },
    {
      field: 'loss',
      width: '150px'
    },
    {
      field: 'loss',
      width: '150px'
    },
    {
      field: 'loss',
      width: '150px'
    },
  ];//表格宽度配置
  MatrialIndex = 0;
  maxHeight = 'calc(100vh - 570px)'
  constructor(private dialogService: DialogService, private ProcessService: ProcessService, private MomService: MomService, private Router: Router, private ToastService: ToastService) { }
  ngOnInit(): void {
    this.display = false
    this.ProcessService.GetPagedProcesss(null, 1, 999).subscribe((res: any) => {
      this.processOptions = res.items
    })
  }
  SelectMaterial(dialogtype?: string,) {
    let data = {
      display: false,
      placeholder: '请选择物料'
    }
    const results = this.dialogService.open({
      id: 'department',
      width: '1000px',
      maxHeight: '800px',
      title: '物料',
      data: data,
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              this.MomData.partId = results.modalContentInstance.selectData.partId;
              this.MomData.partNum = results.modalContentInstance.selectData.partNum;
              this.MomData.partName = results.modalContentInstance.selectData.partName;
              this.MomData.Materials = this.Materials;
              if (this.MomData.momProcesses.length > 0) {
                if (this.MomData.momProcesses[0].processNumber == null) {
                  this.MomData.momProcesses = [];
                }
              }
              results.modalInstance.hide();
              this.treeData = this.transformData(this.MomData);

            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  SelectTechnologyRoute(dialogtype?: string,) {
    let data = {
      display: false,
      placeholder: '请选择工艺路线'
    }
    const results = this.dialogService.open({
      id: 'department',
      width: '700px',
      maxHeight: '800px',
      title: '工艺路线',
      data: data,
      content: SelectTechnologyRouteComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              console.log(results.modalContentInstance.selectData)
              this.display = false
              this.MomData.technologyRouteId = results.modalContentInstance.selectData.technologyRouteId;
              this.MomData.technologyRouteNum = results.modalContentInstance.selectData.technologyRouteNum;
              this.MomData.technologyRouteName = results.modalContentInstance.selectData.technologyRouteName;
              this.ProcessService.GetTechnologyRouteById(results.modalContentInstance.selectData.technologyRouteId).subscribe((res: any) => {
                this.MomData.momProcesses = res.processDetails.map((node: any) => ({
                  ...node,
                  parts: [],
                  isInspection: true,
                  unitTime: 0,
                  pieceWage: node?.pieceWage ?? 0,
                }));
                this.nodes = res.processDetails.map((node: any) => ({
                  ...node,
                  parts: [],
                  isInspection: true,
                  unitTime: 0,
                  pieceWage: node?.pieceWage ?? 0,
                }));

                this.treeData = this.transformData(this.MomData);
              })
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    })
  }
  versionChange($event?: any) {
    this.treeData = this.transformData(this.MomData);
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  onChange($event: any) {
    this.MomData.startDate = $event[0]
    this.MomData.endDate = $event[1]
  }
  addNode(node?: any, index?: any, nextNode?: any) {
    if (this.MomData.technologyRouteNum) {
      if (node) {
        if (nextNode) {
          if (nextNode.processNumber - node.processNumber > 1) {
            const newNode = { processNumber: Math.round((node.processNumber + nextNode.processNumber) / 2), isFirstInspection: false, processId: null, processName: '未设置工序', processNum: null, isOutsourcing: false, parts: [], unitTime: 0, isInspection: false, pieceWage: 0 };
            const index = this.nodes.indexOf(node);
            this.nodes.splice(index + 1, 0, newNode);
            this.MomData.momProcesses = this.nodes.map((node, index) => {
              return {
                ...node,
              };
            })
            this.treeData = this.transformData(this.MomData);
          } else {
            this.showToast('error', '错误', '序号' + node.processNumber + '和序号' + nextNode.processNumber + '中不能添加工序')
          }
        } else {
          const newNode = { processNumber: node.processNumber + 10, isFirstInspection: false, processId: null, processName: '未设置工序', processNum: null, isOutsourcing: false, parts: [], unitTime: 0, isInspection: false, pieceWage: 0 };
          this.nodes.splice(index + 1, 0, newNode);
          this.MomData.momProcesses = this.nodes.map((node, index) => {
            return {
              ...node,
            };
          })
        }
      } else {
        if (!this.nodes[0]?.processNumber) {
          const newNode = { processNumber: 10, isFirstInspection: false, processId: null, processName: '未设置工序', processNum: null, isOutsourcing: false, parts: [], unitTime: 0, isInspection: false, pieceWage: 0 };
          this.nodes.unshift(newNode);
          this.MomData.momProcesses = this.nodes.map((node, index) => {
            return {
              ...node,
            };
          })
          this.treeData = this.transformData(this.MomData);
        }
        else if (this.nodes[0].processNumber) {
          if (this.nodes[0].processNumber > 1) {
            const newNode = { processNumber: Math.round(this.nodes[0].processNumber / 2), isFirstInspection: false, processId: null, processName: '未设置工序', processNum: null, isOutsourcing: false, parts: [], unitTime: 0, isInspection: false, pieceWage: 0 };
            this.nodes.unshift(newNode);
            this.MomData.momProcesses = this.nodes.map((node, index) => {
              return {
                ...node,
              };
            })
            this.treeData = this.transformData(this.MomData);
          } else {
            this.showToast('error', '错误', '序号不能小于1')
          }
        }
      }
    }
    else {
      this.showToast('error', '错误', '请先选择工艺路线！');
    }
  }
  deleteNode(node?: any,) {
    this.nodes = this.nodes.filter(item => item.processNumber !== node.processNumber)
    this.display = false;
    this.MomData.momProcesses = this.nodes.map((node, index) => {
      return {
        ...node,
      };
    })
    this.MomData.Materials = this.Materials;
    this.treeData = this.transformData(this.MomData);
  }
  editNode(node: any, i?: any) {
    this.selectNode = node;
    this.display = true
    this.nodes.forEach(node => {
      node.isClicked = false;
    });
    this.selectNode.isClicked = true;
  }
  selectProcess($event: any) {
    this.selectNode.processId = $event.processId
    this.selectNode.processName = $event.processName
    this.selectNode.processNum = $event.processNum,
      this.MomData.momProcesses = this.nodes.map((node, index) => {
        return {
          ...node,
        };
      })
    this.treeData = this.transformData(this.MomData);

  }
  addMaterial($event?: any, index?: any, nextPart?: any) {
    const maxMaterialNumber = this.getMaxMaterialNumberBeforeCurrentProcess(this.selectNode);
    const minMaterialNumber = this.getMinMaterialNumberAfterCurrentProcess(this.selectNode);
    if (!$event) {
      if (maxMaterialNumber === null && minMaterialNumber === null) {
        this.selectNode.parts.push({
          partId: null,
          partNum: "",
          partName: "",
          partNumber: 10,
          unitUsage: 1,
          lossRate: 0,
          fixedLoss: 0,
          partType: '',
          partUOM: '',
          lossRateDisabled: false,
          fixedLossDisabled: false
        });
      } else if (maxMaterialNumber && minMaterialNumber === null) {
        this.selectNode.parts.push({
          partId: null,
          partNum: "",
          partName: "",
          partNumber: maxMaterialNumber + 10,
          unitUsage: 1,
          lossRate: 0,
          fixedLoss: 0,
          partType: '',
          partUOM: '',
          lossRateDisabled: false,
          fixedLossDisabled: false
        });
      } else if (maxMaterialNumber === null && minMaterialNumber) {
        this.selectNode.parts.push({
          partId: null,
          partNum: "",
          partName: "",
          partNumber: minMaterialNumber - 10,
          unitUsage: 1,
          lossRate: 0,
          fixedLoss: 0,
          partType: '',
          partUOM: '',
          lossRateDisabled: false,
          fixedLossDisabled: false
        });
      } else if (maxMaterialNumber && minMaterialNumber) {
        if (minMaterialNumber - maxMaterialNumber > 1) {
          this.selectNode.parts.push({
            partId: null,
            partNum: "",
            partName: "",
            partNumber: Math.round((maxMaterialNumber + minMaterialNumber) / 2),
            unitUsage: 1,
            lossRate: 0,
            fixedLoss: 0,
            partType: '',
            partUOM: '',
            lossRateDisabled: false,
            fixedLossDisabled: false
          });
        } else {
          this.showToast('error', '错误', '物料号' + maxMaterialNumber + '和物料号' + minMaterialNumber + '之间不能添加物料')
        }
      }
      else {
        this.selectNode.parts.push({
          partId: null,
          partNum: "",
          partName: "",
          partNumber: 10,
          unitUsage: 1,
          lossRate: 0,
          fixedLoss: 0,
          partType: '',
          partUOM: '',
          lossRateDisabled: false,
          fixedLossDisabled: false
        });
      }
    } else {
      if (nextPart) {
        if (nextPart.partNumber - $event.partNumber > 1) {
          this.selectNode.parts.splice(index + 1, 0, {
            partId: null,
            partNum: "",
            partName: "",
            partNumber: Math.round(($event.partNumber + nextPart.partNumber) / 2),
            unitUsage: 1,
            lossRate: 0,
            fixedLoss: 0,
            partType: '',
            partUOM: '',
            lossRateDisabled: false,
            fixedLossDisabled: false
          })
        } else {
          this.showToast('error', '错误', '物料号' + $event.partNumber + '和物料号' + nextPart.partNumber + '之间不能添加物料')
        }
      } else {
        if (minMaterialNumber) {
          if ((minMaterialNumber - $event.partNumber) > 1) {
            this.selectNode.parts.push({
              partId: null,
              partNum: "",
              partName: "",
              partNumber: Math.round((minMaterialNumber + $event.partNumber) / 2),
              unitUsage: 1,
              lossRate: 0,
              fixedLoss: 0,
              partType: '',
              partUOM: '',
              lossRateDisabled: false,
              fixedLossDisabled: false
            });
          } else {
            this.showToast('error', '错误', '物料号' + $event.partNumber + '和物料号' + minMaterialNumber + '之间不能添加物料')
          }
        } else {
          this.selectNode.parts.push({
            partId: null,
            partNum: "",
            partName: "",
            partNumber: $event.partNumber + 10,
            unitUsage: 1,
            lossRate: 0,
            fixedLoss: 0,
            partType: '',
            partUOM: '',
            lossRateDisabled: false,
            fixedLossDisabled: false
          });

        }
      }
    }
    this.Materials = this.nodes.reduce((materials, process) => {
      return materials.concat(process.parts);
    }, []).sort((a: { partNumber: number; }, b: { partNumber: number; }) => a.partNumber - b.partNumber);
    this.MomData.Materials = this.Materials;
    this.MomData.momProcesses = this.nodes
    this.treeData = this.transformData(this.MomData)
  }
  getMaxMaterialNumberBeforeCurrentProcess(selectNode: any): number {
    // 假设你的所有工序存储在一个名为this.processes的数组中
    let maxMaterialNumber = -Infinity;// 用于存储最大的物料序号
    for (let i = 0; i < this.nodes.length; i++) {
      let process = this.nodes[i];
      if (process === selectNode) {
        break;
      }
      if (process.parts && process.parts.length > 0) {
        // 获取这个工序的最大物料序号
        let maxNumberInProcess = Math.max(...process.parts.map((material: { partNumber: any; }) => material.partNumber));
        maxMaterialNumber = Math.max(maxMaterialNumber, maxNumberInProcess);
      }
    }
    // 如果没有找到任何有物料的工序，返回10作为默认的物料序号
    return maxMaterialNumber === -Infinity ? null : maxMaterialNumber;
  }
  getMinMaterialNumberAfterCurrentProcess(selectNode: any): number {
    // 假设你的所有工序存储在一个名为this.processes的数组中
    let minMaterialNumber = Infinity;
    let foundCurrentProcess = false;
    for (let i = 0; i < this.nodes.length; i++) {
      let process = this.nodes[i];
      if (process === selectNode) {
        foundCurrentProcess = true;
        continue;
      }
      if (foundCurrentProcess && process.parts && process.parts.length > 0) {
        // 获取这个工序的最小物料序号
        let minNumberInProcess = Math.min(...process.parts.map((material: { partNumber: any; }) => material.partNumber));
        minMaterialNumber = Math.min(minMaterialNumber, minNumberInProcess);
      }
    }
    // 如果没有找到任何有物料的工序，返回10作为默认的物料序号
    return minMaterialNumber === Infinity ? null : minMaterialNumber;
  }
  editingChange(rowItem: any) {
    let Index = this.Materials.findIndex(item => item.partNumber === rowItem.partNumber);
    this.MatrialIndex = Index;
    this.originalPartNumber = rowItem.partNumber;
  }
  removeMaterial(i: number, partNumber: any) {
    this.selectNode.parts.splice(i, 1);
    this.Materials = this.Materials.filter(material => material.partNumber !== partNumber);
    this.MomData.Materials = this.Materials;
    this.treeData = this.transformData(this.MomData);
  }
  processNumberChange() {
    this.nodes.sort((a, b) => a.processNumber - b.processNumber);
    this.MomData.momProcesses = this.nodes.map((node, index) => {
      return {
        ...node,
      };
    })
    this.treeData = this.transformData(this.MomData);
  }
  processNumber(value: any) {
    let res = true;
    let processNumbers = this.MomData.momProcesses.map(process => process.processNumber);
    let duplicates = processNumbers.filter((item, index) => processNumbers.indexOf(item) != index);

    if (duplicates.length > 0) {
      res = false;
    }
    return of(res).pipe(delay(100))
  }
  SelectMaterials(index: number, partNumber?: any, dialogtype?: string,) {
    let data = {
      display: false,
      placeholder: '请选择物料'
    };
    const results = this.dialogService.open({
      id: 'department',
      width: '1000px',
      title: '物料',
      data: data,
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              if (this.MaterialData.some(item => item.code === results.modalContentInstance.selectData.partId)) {
                this.showToast('error', '错误', '不能重复选择物料');
              } else {
                this.selectNode.parts[index].partId = results.modalContentInstance.selectData.partId;
                this.selectNode.parts[index].partNum = results.modalContentInstance.selectData.partNum;
                this.selectNode.parts[index].partName = results.modalContentInstance.selectData.partName;
                this.selectNode.parts[index].unitUsage = 1;
                this.selectNode.parts[index].lossRate = 0;
                this.selectNode.parts[index].fixedLoss = 0;
                this.selectNode.parts[index].partType = results.modalContentInstance.selectData.partType;
                this.selectNode.parts[index].partUOM = results.modalContentInstance.selectData.partUOM;
                delete this.selectNode.parts[index].codeEdit;
                let Material = this.Materials.find(Material => Material.partNumber === partNumber);
                Material.partId = results.modalContentInstance.selectData.partId;
                Material.partNum = results.modalContentInstance.selectData.partNum;
                Material.partName = results.modalContentInstance.selectData.partName;
                Material.unitUsage = 1;
                Material.lossRate = 0;
                this.MomData.Materials = this.Materials;
                this.treeData = this.transformData(this.MomData);
              }
              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          },
        },
      ],
    });
  }//物料物料
  partNumberRule: boolean = false;
  partNumberChange($event: any, rowIndex?: any) {
    if (this.Materials.some(item => item.partNumber === $event)) {
      this.showToast('error', '错误', '已有相同物料号');
      this.selectNode.parts[rowIndex].partNumber = this.originalPartNumber;
      this.Materials[this.MatrialIndex].partNumber = this.originalPartNumber;
    } else {
      this.Materials[this.MatrialIndex].partNumber = $event;
      this.Materials.sort((a, b) => a.partNumber - b.partNumber);
      this.selectNode.parts.sort((a: { partNumber: number; }, b: { partNumber: number; }) => a.partNumber - b.partNumber);
      this.MomData.Materials = this.Materials;
      this.treeData = this.transformData(this.MomData);
    }
  }
  submit($event: any) {
    if ($event.valid) {
      this.ProcessDetails = this.nodes.map(({ isClicked, ...rest }) => rest)
      this.ProcessDetails = this.ProcessDetails.map((node, index) => {
        return {
          ...node,
          processNumber: node.processNumber,
          parts: node.parts,
        };
      });
      this.MomData.momProcesses = this.ProcessDetails;
      this.MomData = { ...this.MomData };
      delete this.MomData.Materials;
      const includeKeys = ['partNum', 'partName', 'version', 'technologyRouteId', 'technologyRouteNum', 'technologyRouteName', 'startDate', 'endDate', 'momProcesses', 'unitTime', 'unitUsage', 'partNumber', 'processName', 'processNum', 'processNumber'];
      const keyMap = {
        'partNum': '物料编码',
        'partName': '物料名称',
        'version': '版本',
        'technologyRouteId': '工艺路线ID',
        'technologyRouteNum': '工艺路线编码',
        'technologyRouteName': '工艺路线名称',
        'startDate': '开始日期',
        'endDate': '结束日期',
        'processId': '工序ID',
        'processName': '工序名称',
        'processNum': '工序编码',
        'processNumber': '工序序号',
        'unitTime': '单位工时',
        'partId': '物料ID',
        'partNumber': '物料序号',
        'unitUsage': '单位用量'
      };

      const errors = this.checkEmptyProperties(this.MomData, '', includeKeys, keyMap);
      if (errors.length > 0) {
        this.showToast('wran', '错误', errors[0])
      }
      if (errors.length === 0) {
        this.MomService.CreateMOM(this.MomData).subscribe(
          (res: any) => {
            this.showToast('success', '成功', '添加成功')
            setTimeout(() => {
              this.Router.navigate(['/pages/process/mom'])
            }, 1000)
          },
          (error) => {
            if (error.status == 404) {
              this.showToast('error', '失败', '服务器连接失败');
            } else {
              this.showToast('error', '失败', error.error);
            }
          }
        )
      }
    } else {
      this.showToast('error', '错误', '请检查表单')
    }
  }
  transformData(data: any) {
    return [
      {
        title: data.partName + " 版本：" + data.version,
        open: true,
        treeId: "mom",
        icon: { icon: 'icon-unarchived-item' },
        showCheckbox: false,
        disableDelete: true,
        items: [
          {
            title: '工序',
            open: true,
            treeId: "process",
            icon: { icon: 'icon-merge-request2' },
            showCheckbox: false,
            disableDelete: true,

            items: data.momProcesses.map((detail: { processNumber: any, processName: any; processId: any; parts: any[]; }) => ({
              title: "工序" + detail.processNumber + "： " + detail.processName,
              data: detail,
              open: true,
              showCheckbox: false,
              disableDelete: true,
              icon: { icon: 'icon-tag' },
              items: detail.parts.map(part => ({
                title: "物料" + part.partNumber + "： " + part.partName,
                data: part,
                showCheckbox: false,
                disableDelete: true,
                icon: { icon: '' },
              }))
            }))
          }, {
            title: "物料",
            open: true,
            treeId: "process",
            showCheckbox: false,
            disableDelete: true,
            icon: { icon: 'B' },
            items: data.Materials.map((material: { partNumber: any; partName: any; partId: any; }) => ({
              title: "物料" + material.partNumber + "： " + material.partName,
              data: material,
              showCheckbox: false,
              disableDelete: true,
              icon: { icon: '' },
            }))
          }
        ]
      }
    ];
  }
  cancle() {
    this.Router.navigate(['/pages/process/mom'])
  }
  preview(dialogtype?: string) {
    const results = this.dialogService.open({
      width: '1000px',
      title: 'MOM预览',
      backdropCloseable: false,
      data: {
        nodes: this.nodes
      },
      content: PreViewmMomComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  onButtonClick(dialogtype?: string) {
    const results = this.dialogService.open({
      title: 'MOM附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: 'MOM附件',
        urls: this.MomData.fileURL
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.MomData.fileURL = results.modalContentInstance.urls;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  lossRateChange($event: any, rowItem: any) {
    rowItem.lossRate = $event / 100
    if ($event > 0) {
      rowItem.fixedLossDisabled = true;
    } else {
      rowItem.fixedLossDisabled = false;
    }
  }
  fixedLossChange($event: any, rowItem: any) {
    if ($event > 0) {
      rowItem.lossRateDisabled = true;
    } else {
      rowItem.lossRateDisabled = false;
    }
  }
  checkEmptyProperties(obj: any, parentKey = '', includeKeys = [], keyMap = {}) {
    let emptyProperties = [];
    for (let key in obj) {
      // 如果当前属性不在包含列表中，跳过检查
      if (!includeKeys.includes(key)) {
        continue;
      }
      let fullKey = parentKey ? `${parentKey}.${key}` : key;
      let mappedKey = keyMap[key] || key; // 使用映射对象获取属性的中文名，如果没有映射，就使用原名
      if (obj[key] && typeof obj[key] === 'object') {
        if (Array.isArray(obj[key]) && key === 'momProcesses') {
          console.log(obj[key])
          obj[key].forEach((item, index) => {
            let processName = item.processName || '';
            let processNumber = item.processNumber || '';
            let childKey = `工序${processNumber}:${processName}`; // 添加'工序'、工序的索引和工序的名称
            emptyProperties = emptyProperties.concat(this.checkEmptyProperties(item, childKey, includeKeys, keyMap));

            // 如果工序下存在物料，遍历物料并检查物料的属性
            if (item.parts) {
              item.parts.forEach((material, materialIndex) => {
                let materialName = material.partName || '';
                let materialNumber = material.partNumber || '';
                let materialKey = `${childKey}的物料${materialNumber}${materialName}`; // 添加'物料'、物料的索引和物料的名称
                emptyProperties = emptyProperties.concat(this.checkEmptyProperties(material, materialKey, includeKeys, keyMap));
              });
            }
          });
        } else {
          emptyProperties = emptyProperties.concat(this.checkEmptyProperties(obj[key], fullKey, includeKeys, keyMap));
        }
      } else if (obj[key] === undefined || obj[key] === null || obj[key] === '' || (typeof obj[key] === 'number' && obj[key] <= 0 && includeKeys.includes(key))) {
        let errorKey = parentKey ? `${parentKey}.${mappedKey}` : mappedKey;
        errorKey = errorKey.replace('momProcesses.', '').replace(/\./g, '的'); // 在生成错误信息时，移除'momProcesses.'，并将'.'替换为'的'
        emptyProperties.push(errorKey + ' 不能为空');
      } else if (typeof obj[key] === 'number' && obj[key] <= 0 && !includeKeys.includes(key)) {
        let errorKey = parentKey ? `${parentKey}.${mappedKey}` : mappedKey;
        errorKey = errorKey.replace('momProcesses.', '').replace(/\./g, '的'); // 在生成错误信息时，移除'momProcesses.'，并将'.'替换为'的'
        emptyProperties.push(errorKey + ' 不能小于等于0');
      }
    }
    return emptyProperties;
  }
}
